using System.Linq;
using Cysharp.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace EasyLocalization.Editor
{
    [CustomEditor(typeof(LocalizationDictionary), true)]
    public class LocalizationDictionaryInspector : UnityEditor.Editor
    {
        LocalizationDictionary _target;
        string[] _currentLanguageOptions;

        void OnEnable()
        {
            _target = target as LocalizationDictionary;
            _currentLanguageOptions = CreateCurrentLanguageOptions();
        }

        public override void OnInspectorGUI()
        {
            var iter = serializedObject.GetIterator();
            iter.Next(true);
            EditorGUI.BeginChangeCheck();
            while (iter.NextVisible(false))
            {
                if (iter.name.Contains("Script"))
                {
                    continue;
                }

                if (iter.name == LocalizationDictionary.currentLanguageFieldName)
                {
                    RenderCurrentLanguageView(iter);
                    continue;
                }
                
                EditorGUILayout.PropertyField(iter);
            }

            if (EditorGUI.EndChangeCheck())
            {
                _currentLanguageOptions = CreateCurrentLanguageOptions();
                serializedObject.ApplyModifiedProperties();
            }

            if (GUILayout.Button("Reload"))
            {
                _target.ReloadAsync().Forget();
            }
        }

        void RenderCurrentLanguageView(SerializedProperty iter)
        {
            if (_target.languages == null)
            {
                return;
            }
            
            SerializedProperty clSp = iter.FindPropertyRelative("value");
            int index = 0;
            for (int i = 0; i < _target.languages.Count; i++)
            {
                Language language = _target.languages[i];
                if (language.keyName == clSp.stringValue)
                {
                    index = i;
                    break;
                }
            }

            int newIndex = EditorGUILayout.Popup(iter.displayName, index, _currentLanguageOptions);
            if (newIndex != index)
            {
                clSp.stringValue = _target.languages[newIndex].keyName;
                _target.LoadAsync(clSp.stringValue).Forget();
            }
            clSp.Dispose();
        }

        string[] CreateCurrentLanguageOptions()
        {
            return _target.languages
                .Select(x => x.localizedName)
                .ToArray();
        }
    }
}